In this step-by-step article descrbes how to create a MS word document file using asp.net. The sample code in this article demonstrates how to insert paragraphs with text programmatically. Inorder to create we need to install docX using nuget package console.
PM> Install-Package DocX
Step 1: Create a class and name it as Document in the model folder.
public class Document
{
public string txtContent { get; set; }
}
Step 2: Right click on the "Controllers" folder and add "doc" controller. Copy and paste the following code. Please make sure to include "MVC_tutorials.Models" namespace.
using MVC_tutorials.Models;
using Novacode;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVC_tutorials.Controllers
{
public class docController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(Documentdocument)
{
string fileName = Server.MapPath(@"~\DocXExample.docx");
// Create a document in memory:
var doc = DocX.Create(fileName);
// Insert a paragrpah:
doc.InsertParagraph(document.txtContent);
// Save to the output directory:
doc.Save();
TempData["Message"] = "document created successfully.";
return View();
}
}
}
Step 3: Right click on the "Index" action method in the "docController" and add "Index" view. Copy and paste the following code.
@model MVC_tutorials.Models.Document
@{
ViewBag.Title = "create document in asp.net MVC";
}
<style type="text/css">
.btn {
width: 150px;
height: 50px;
background: #00BCD4;
border-style: solid;
border-color: white;
color: white;
}
</style>
<div style="padding-top: 15px">
<h2 style="color: #FF5722">create document in asp.net MVC
</h2>
@using (@Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
if (TempData["Message"] != null)
{
<p style="font-family: Arial; font-size: 16px; font-weight: 200; color: #56772F">@TempData["Message"]</p>
}
@Html.TextAreaFor(model => model.txtContent, new { Class = "mytextstyle", rows = 5, Style = "width:450px", placeholder = "type your content and save it in adocument." })
<br />
<input type="submit" value="create document" class="btn" />
}
</div>
Output:
Post your comments / questions
Recent Article
- How to create custom 404 error page in Django?
- Requested setting INSTALLED_APPS, but settings are not configured. You must either define..
- ValueError:All arrays must be of the same length - Python
- Check hostname requires server hostname - SOLVED
- How to restrict access to the page Access only for logged user in Django
- Migration admin.0001_initial is applied before its dependency admin.0001_initial on database default
- Add or change a related_name argument to the definition for 'auth.User.groups' or 'DriverUser.groups'. -Django ERROR
- Addition of two numbers in django python
Related Article